package com.dz.lm.web.controller.newuser.userapply;

import com.alibaba.fastjson.JSONObject;
import com.dz.lm.common.dto.UserApplyDTO;
import com.dz.lm.common.dto.UserProductDTO;
import com.dz.lm.common.exception.DaoException;
import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.common.util.FileUploadUtil;
import com.dz.lm.common.util.JPushUtils;
import com.dz.lm.common.util.StringUtil;
import com.dz.lm.common.utils.json.JsonUtils;
import com.dz.lm.service.pay.WxPayService;
import com.dz.lm.service.userapply.UserApplyService;
import com.dz.lm.service.userorder.UserOrderService;
import com.dz.lm.service.userproduct.UserProductService;
import com.dz.lm.web.controller.BasicControl;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

/**
 * 产品申请控制层
 *
 * @version 1.8;
 * @author: LDY;
 * @Description;
 * @Date: Created in 2020/3/13 21:24;
 */
@RestController
@RequestMapping(value = "/h5/weijie/rewriteUrl/userApply", produces = "application/json")
public class UserApplyContorller extends BasicControl {
    @Autowired
    private UserApplyService userApplyService;
    @Autowired
    private UserProductService userProductService;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private UserOrderService userOrderService;

    @Resource(name="readLoginLogDao")
    private com.dz.lm.dao.log.read.LoginLogDao loginLogDao;
    /**
     * 操作申请
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/add")
    public Map add(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "";
        Object data = null;
        JSONObject subjo = new JSONObject();
        Object imgUrl = request.getAttribute("imgUrl");
        Map<String, Object> images = (Map<String, Object>) request.getAttribute("images");
        Map<String, Object> urlMap = new HashMap<String, Object>();
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        Map<String, Object> param = JsonUtils.readValue(reqData.toString());
        if (images != null && !images.isEmpty()) {
            urlMap = FileUploadUtil.uploadByInStream(images, imgUrl, "apply");
        }
        //参数校验
        Vector<String> inparam = new Vector<String>();

        //用户
        Integer userId = param.get("userId") != null ? Integer.parseInt(param.get("userId").toString()) : 0;
        //原生产品
        Integer productId = param.get("productId") != null ? Integer.parseInt(param.get("productId").toString()) : 0;
        //备注
        String remark = param.get("remark") != null ? param.get("remark").toString() : "";
        //模板json
        String template = param.get("template") != null ? param.get("template").toString() : "";
        //province	省市编码
        String province = param.get("province") != null ? param.get("province").toString() : "110100";
        //city	城市编码
        String city = param.get("city") != null ? param.get("city").toString() : "";
        //区
        String area = param.get("area") != null ? param.get("area").toString() : "";
        //价格
        double price = param.get("price") != null ? Double.parseDouble(param.get("price").toString()) : 0;
        //小程序标识
        String wxcode = param.get("wxcode") != null ? param.get("wxcode").toString() : "";
        StringBuilder urlsbulidr = new StringBuilder();
        if (images != null && !images.isEmpty()) {
            for (String key : images.keySet()) {
                urlsbulidr.append(imgUrl + urlMap.get(key).toString() + ",");
            }
        }

        String urls = urlsbulidr.toString();
        if ( userId == 0 || productId == 0) {
            message = "参数有误";
            result = "02";
        } else {
            int applyId = userApplyService.add(userId, productId, remark, template, urls,param.get("platform").toString(),province,city,area,price);
            if (applyId > 0) {
                message = "操作成功";
                result = "00";
                Map map = new HashMap();
                map.put("applyId",applyId);
                data =map;
                if(price > 0){ //吊起微信支付
                    map.put("amount", price);
                    map.put("userId", userId);
                    map.put("gather",productId);
                    map.put("orderType", 9);
                    map.put("applyId", applyId);
                    map.put("type", 4);//申请订单支付
                    map.put("body", "订单支付");
                    map.put("productId", productId);
                    map.put("platform", param.get("platform"));
                    if(!StringUtil.containEmpty(wxcode)){
                        map.put("wxcode", wxcode);
                    }
                    Map<String, Object> retData = wxPayService.unifiedOrder(map);
                    map.putAll(retData);

                }
            } else if (applyId == -998) {
                message = "申请已被拒绝30内无法再次申请";
                result = "02";
            }
        }
        if (param.get("platform").equals("Android")) {
            Map<String, Object> retData = new HashMap();
            retData.put("message", message);
            retData.put("result", result);
            retData.put("data", data);
            subjo.putAll(retData);
            return parameterEncrypt(request, subjo);
        } else {
            subjo.put("message", message);
            subjo.put("result", result);
            subjo.put("data", data);
            return subjo;
        }
    }

    /**
     * 申请列表
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/list")
    public Map list(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "";
        Object data = null;
        JSONObject subjo = new JSONObject();
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        //  String uId = request.getAttribute("uersId").toString();
        Map<String, Object> param = JsonUtils.readValue(reqData);
        //受请人
        Integer supUid = param.get("supUid") != null ? Integer.parseInt(param.get("supUid").toString()) : 0;
        //申请人
        Integer subUid = param.get("subUid") != null ? Integer.parseInt(param.get("subUid").toString()) : 0;
        //代理人
        Integer agentUid = param.get("agentUid") != null ? Integer.parseInt(param.get("agentUid").toString()) : 0;

        //产品
        Integer productId = param.get("productId") != null ? Integer.parseInt(param.get("productId").toString()) : 0;
        //staus 1 待接单 2拒绝 3-已提交
        Integer status = param.get("status") != null ? Integer.parseInt(param.get("status").toString()) : 0;
        Integer pageNum = param.get("page") != null ? Integer.parseInt(param.get("page").toString()) : 1;
        Integer rows = param.get("rows") != null ? Integer.parseInt(param.get("rows").toString()) : 10;
        data = userApplyService.query(pageNum + 1, rows, supUid, subUid, agentUid, productId, status);
        message = "获取成功";
        result = "00";
        if (param.get("platform").equals("Android")) {
            Map<String, Object> retData = new HashMap();
            retData.put("message", message);
            retData.put("result", result);
            retData.put("data", data);
            subjo.putAll(retData);
            return parameterEncrypt(request, subjo);
        } else {
            subjo.put("message", message);
            subjo.put("result", result);
            subjo.put("data", data);
            return subjo;
        }
    }

    /**
     * 处理申请
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/handleApply")
    public Map handleApply(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "";
        Object data = null;
        JSONObject subjo = new JSONObject();
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        String uId = request.getAttribute("userId") != null ? request.getAttribute("userId").toString() : "";
        Map<String, Object> param = JsonUtils.readValue(reqData.toString());
        //参数校验
        Vector<String> inparam = new Vector<String>();

        for (String in : inparam) {
            if (!param.containsKey(in)) {
                subjo = new JSONObject();
                subjo.put("result", "01");
                subjo.put("message", "参数" + in + "异常");
                return subjo;
            }
        }
        //申请id
        Integer applyId = param.get("applyId") != null ? Integer.parseInt(param.get("applyId").toString()) : 0;
        //产品
        Integer productId = param.get("productId") != null ? Integer.parseInt(param.get("productId").toString()) : 0;
        //状态 1 待接单 2拒绝 3-已提交同意申请 4已接单
        Integer status = param.get("status") != null ? Integer.parseInt(param.get("status").toString()) : 0;
        //通过 输入成交金额
        double amount = param.get("amount") != null ? Double.parseDouble(param.get("amount").toString()) : 0.00;
        //备注
        String remark = param.get("remark") != null ? param.get("remark").toString() : "";
        //小程序标识
        String wxcode = param.get("wxcode") != null ? param.get("wxcode").toString() : "";
        //申请通过推送
        String applyContent = param.get("applyContent") != null ? param.get("applyContent").toString() : "";

        if (applyId == 0) {
            message = "参数有误";
            result = "02";
        } else if(amount >0 && amount <10){
            message = "成交金额至少大于10元。";
            result = "01";
        }else {
            UserApplyDTO apply = userApplyService.getDetail(applyId, 0, 0, 0);

            int i = userApplyService.handleApply(applyId, status, amount, productId,remark,apply,applyContent,param.get("platform").toString());
            if (i > 0) {
                if (status == 3) { //同意申请,有返点时调微信支付
                    UserProductDTO product = userProductService.getDetail(0, productId, false);
                    if(apply.getAgentUid()>0 && apply.getRePoint() >0){ //有代理人，返点大于0
                        BigDecimal amountC = new BigDecimal(amount);
                        BigDecimal returnPoint = new BigDecimal(product.getReturnPoint());
                        BigDecimal re_point = null;
                        re_point = amountC.multiply(returnPoint);
                        DecimalFormat df1 = new DecimalFormat("0.00");
                        double rePoint = Double.parseDouble(df1.format(re_point));
                        if (rePoint > 0) {
                            Map map = new HashMap();
                            map.put("userId", StringUtil.getInt(uId, 0));
                            map.put("amount", rePoint / 100);
                            map.put("orderType", 5);
                            map.put("agentUid", apply.getAgentUid());
                            map.put("applyId", applyId);
                            map.put("rePoint", rePoint/100);
                            map.put("type", 2);//返点
                            map.put("body", "代理返点费用");
                            map.put("platform", param.get("platform"));
                            if(!StringUtil.containEmpty(wxcode)){
                                map.put("wxcode", wxcode);
                            }
                            Map<String, Object> retData = wxPayService.unifiedOrder(map);
                            data = retData;
                        }
                    }
                }
                message = "操作成功";
                result = "00";
            }
        }
        if (param.get("platform").equals("Android")) {
            Map<String, Object> retData = new HashMap();
            retData.put("message", message);
            retData.put("result", result);
            retData.put("data", data);
            subjo.putAll(retData);
            return parameterEncrypt(request, subjo);
        } else {
            subjo.put("message", message);
            subjo.put("result", result);
            subjo.put("data", data);
            return subjo;
        }
    }

    /**
     * 查看详情
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/getDetail")
    public Map getDetail(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "";
        Object data = null;
        JSONObject subjo = new JSONObject();
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        Map<String, Object> param = JsonUtils.readValue(reqData.toString());
        //参数校验
        Vector<String> inparam = new Vector<String>();

        for (String in : inparam) {
            if (!param.containsKey(in)) {
                subjo = new JSONObject();
                subjo.put("result", "01");
                subjo.put("message", "参数" + in + "异常");
                return subjo;
            }
        }
        //申请id
        Integer applyId = param.get("applyId") != null ? Integer.parseInt(param.get("applyId").toString()) : 0;
        //受请人
        Integer supUid = param.get("supUid") != null ? Integer.parseInt(param.get("supUid").toString()) : 0;
        //申请人
        Integer subUid = param.get("subUid") != null ? Integer.parseInt(param.get("subUid").toString()) : 0;
        //代理人
        Integer agentUid = param.get("agentUid") != null ? Integer.parseInt(param.get("agentUid").toString()) : 0;


        if (applyId == 0) {
            message = "参数有误";
            result = "02";
        } else {
            data = userApplyService.getDetail(applyId, supUid, subUid, agentUid);
            message = "操作成功";
            result = "00";
        }
        if (param.get("platform").equals("Android")) {
            Map<String, Object> retData = new HashMap();
            retData.put("message", message);
            retData.put("result", result);
            retData.put("data", data);
            subjo.putAll(retData);
            return parameterEncrypt(request, subjo);
        } else {
            subjo.put("message", message);
            subjo.put("result", result);
            subjo.put("data", data);
            return subjo;
        }
    }
    public class AsyncThread implements Runnable {
        private Map<String, Object> param;

        AsyncThread(Map<String, Object> param) {
            this.param = param;
        }
        @Override
        public void run() {
            try {
                pushMessage(param);
            } catch (ServiceException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 消息推送
     */
    private void pushMessage(Map<String, Object> param) throws ServiceException {
        Map<String, Object> pushInfo = null;
        Map<String, String> map_jp = Maps.newHashMap();
        try {
            pushInfo = loginLogDao.qryPushIdByUserId(param);
            if (pushInfo == null || pushInfo.isEmpty() || pushInfo.get("pushId") == null || "".equals(pushInfo.get("pushId"))) {
                return;
            }
            String pushTitle = "【微介】代理人申请提醒";
            String pushContent = "您有新申请，请注意查收";
            // 推送
            if ("Android".equals(param.get("platform"))) {
                // jpush
                String deviceAndro = pushInfo.get("pushId").toString();
                //push消息
//                JPushUtils.pushAndroidMessageByRegistrationID(pushTitle, pushContent, deviceAndro);
                JPushUtils.pushAndroidNotificationByRegistrationID(pushTitle, pushContent, new HashMap(),deviceAndro);
            } else {
                String[] deviceIos = param.get("IOS").toString().split(",");
                JPushUtils.pushIosNotificationByRegistrationID(pushContent, map_jp, deviceIos);
            }
            logger.info("消息推送成功");
        }
        catch (DaoException e) {
            logger.info("消息推送失败");
            throw new ServiceException(e.getCause());
        }
    }
}
